package br.ita.trucocearense.cliente.core;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;

import br.ita.trucocearense.cliente.core.interfaces.padraobserver.Observer;
import br.ita.trucocearense.cliente.core.interfaces.padraobserver.Subject;
import br.ita.trucocearense.cliente.core.padraoobserver.SubjectImpl;
import br.ita.trucocearense.common.core.interfaces.remote.MesaRemota;
import br.ita.trucocearense.common.core.interfaces.remote.padraoobserver.RemoteObserver;


public class Mesa extends SubjectImpl implements RemoteObserver {
	
	private String[] usuariosMesa = new String[4];
	private Usuario userAtual;
	private MesaRemota mesaServer;


	public Mesa(Usuario userAtual) {
		this.userAtual = userAtual;
		try {
			UnicastRemoteObject.exportObject(this);
			this.getServer().registerObserver(this);
        }
        catch(Exception re) {
            re.printStackTrace();
        }
	}

	public Usuario getUserAtual() {
		return userAtual;
	}

	public void setUsuariosMesa(String[] usuarios) {
		this.usuariosMesa = usuarios;
	}


	public String[] getUsuariosMesa() {
		return usuariosMesa;
	}

	public void sincronizaMesa(){
		try {
			this.setUsuariosMesa(this.getServer().getUsuariosMesa());
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void insereUsuarioMesa(int pos){
		this.userAtual.setPosicaoMesa(pos);
		try {
			this.getServer().insereUsuarioMesa(pos, this.userAtual.getLogin(),this.userAtual.getSenha(),this.userAtual.getApelido(),this.userAtual.getScore());
		} catch (RemoteException e) {
			
			e.printStackTrace();
		}
	}
	
	public void removeUsuarioMesa(){
		int posicao = this.getUserAtual().getPosicaoMesa();
		this.getUserAtual().setPosicaoMesa(-1);
		try {
			this.getServer().removeUsuarioMesa(posicao);
			
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public MesaRemota getServer(){
		if (mesaServer != null)
			return mesaServer;
		try {			
			System.setSecurityManager(new RMISecurityManager());
			this.mesaServer = (MesaRemota) Naming.lookup("rmi://" + getIPServer() + "/mesaremota");			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mesaServer;		
	}

	private String getIPServer() {
		try {
			BufferedReader reader =  new BufferedReader(
					new FileReader(System.getProperty("user.dir") + File.separator + "IPServer.txt"));
			return reader.readLine();
		} catch (Exception e) {
			return "localhost";
		}		
	}
	
	@Override
	public void update(String reference) throws RemoteException {
		notifyObservers(reference);		
	}	
	
}
